<?php
class Weibo
{
	private $appid;
	private $apikey;
	private $secretkey;
	
	function __construct($appid,$apikey,$secretkey)
	{
		$this->appid = $appid;
		$this->apikey = $apikey;
		$this->secretkey = $secretkey;
	}
	
	/**
	 * Make an HTTP request
	 *
	 * @return string API results
	 * @ignore
	 */
	function http($url, $data = array())
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		//如果是post请求
		if( is_array($data) )
		{
			curl_setopt($ch, CURLOPT_POST, 0);
			curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
		}
		$output = curl_exec($ch);
		curl_close($ch);
		return $output;
	}
	
	/**
	* 获得微信登录地址
	* @param 参数1，回调地址。
	*/
	function CreateLoginUrl($backurl)
	{
		//不用获取用户信息信息
		$url="https://api.weibo.com/oauth2/authorize?client_id=".$this->appid."&response_type=code&redirect_uri=".urlencode($backurl);
		return $url;
	}
	
	
	/**
	* 获得access_token
	*/
	function GetToken($backurl)
	{
		$code = input('code');
		if($code){
			$url = 'https://api.weibo.com/oauth2/access_token?client_id='.$this->appid.'&client_secret='.$this->secretkey.'&grant_type=authorization_code&redirect_uri='.$backurl.'&code='.$code;
			$data = json_decode($this->http($url),true);
			return $data;
		}else{
			header('location:'.str_replace("/login/callback","",$backurl));
			exit();
		}
	}
	
	/**
	* 获得用户信息
	*/
	function GetUserInfo($access_token,$openid)
	{
		if(!empty($access_token)){
			//$url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&grant_type=snsapi_userinfo';
			$url = "https://api.weibo.com/2/users/show.json?access_token=".$access_token."&uid=".$openid;
			$data = json_decode(file_get_contents($url),true);
			return $data;
		}
	}
}
